import urllib.parse
import requests
from flask import Blueprint, jsonify, request, render_template, session

chat_service = Blueprint("chat_service", __name__)


@chat_service.before_request
def session_checker():
    if 'user_id' not in session:
        return render_template('401.html')


@chat_service.route("/api/chat")
def chat():
    key = request.args.get("key")
    appid = request.args.get("appid")
    msg = request.args.get("msg")
    data = {"key": key, "appid": appid, "msg": msg}
    query = urllib.parse.urlencode(data)
    src = "http://api.qingyunke.com/api.php?" + query
    r = requests.post(src)
    returnjson = r.content.decode('utf8')
    sentence = eval(returnjson)
    return jsonify({'data': sentence})


@chat_service.route("/chat")
def get_chat():
    return  render_template('chat_api.html')